package cn.lifeaid.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.lifeaid.db.SysRole;
import cn.lifeaid.db.SysUser;
import cn.lifeaid.service.SysOrganizationService;
import cn.lifeaid.service.SysRoleService;
import cn.lifeaid.service.SysUserService;

@Controller
@RequestMapping("/user")
public class SysUserController {

	@Autowired
	private SysUserService userService;
	@Autowired
	private SysOrganizationService organizationService;
	@Autowired
	private SysRoleService roleService;

	@RequiresPermissions("user:view")
	@RequestMapping(method = RequestMethod.GET)
	public String showList(Model uiModel) {
		// 加载用户列表
		List<SysUser> userList = userService.findAll();
		
		uiModel.addAttribute("userList", userList);
		
		//获取用户所属角色
		
		return "user/list";
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String showCreateForm(Model uiModel) {
		setCommonData(uiModel);
		uiModel.addAttribute("user", new SysUser());
		uiModel.addAttribute("op", "新增");
		return "user/edit";
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(SysUser user, RedirectAttributes redirectAttributes) {
		userService.createUser(user);
		redirectAttributes.addFlashAttribute("msg", "新增成功");
		return "redirect:/user";
	}

	private void setCommonData(Model uiModel) {
		uiModel.addAttribute("organizationList", organizationService.findAll());
		uiModel.addAttribute("roleList", roleService.findAll());
	}
}
